package com.example.phone.account.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.AppCompatCheckBox;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.phone.R;
import com.example.phone.account.adapter.AddressRecycleAdapter;
import com.example.phone.base.BaseActivity;
import com.example.phone.base.MyApp;
import com.example.phone.base.RequestInterface;
import com.example.phone.base.ServerResponse;
import com.example.phone.bean.Constants;
import com.example.phone.bean.User;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2018\12\27 0027.
 */

public class AddAddressActivity extends BaseActivity {
    final int UPDATE_SUCCESS = 1;
    @BindView(R.id.go_back)
    ImageView goBack;
    @BindView(R.id.save)
    TextView save;
    @BindView(R.id.receiver_name)
    EditText receiverName;
    @BindView(R.id.phone)
    EditText phone;
    @BindView(R.id.address)
    EditText address;
    @BindView(R.id.page_name)
    TextView page_name;


    /**
     * 值将由上一个界面传过来
     */
    int shippingId;
    String str_receiverName;
    String str_phone;
    String province;
    String city;
    String str_address;
    boolean bo_defaultAddress;

    /**
     * 决定跳转的页面和执行的相关操作
     */
    int page;

    /**
     * 用户
     */
    User user;

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case UPDATE_SUCCESS:

                    Intent intent = new Intent(getContext(), ManageActivity.class);
                    startActivity(intent);

                    break;
            }

        }
    };

    @Override
    public void initData() {
        Intent intent = getIntent();
        page = intent.getIntExtra("page", -1);


        if (page == Constants.EDIT_ADDRESS) {
            Bundle bundle = intent.getBundleExtra("bundle");



            receiverName.setText(bundle.getString("receiver"));
            phone.setText(bundle.getString("telephone"));
            address.setText( bundle.getString("address"));

            shippingId = intent.getIntExtra("shippingId", -1);

        } else if(page == Constants.ADD_ADDRESS) {
            MyApp myApp = (MyApp) getApplication();
            user = myApp.getUser();

        }

    }

    @Override
    public void initView() {
        ButterKnife.bind(this);

    }

    void initPage() {
        if (page == Constants.EDIT_ADDRESS) {
            page_name.setText("编辑收货地址");
        } else if(page == Constants.ADD_ADDRESS) {
            page_name.setText("新增收货地址");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initPage();
    }

    @Override
    public int initLayout() {
        return R.layout.edit_receive_address_layout;
    }


    @OnClick({R.id.go_back, R.id.save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.go_back:
                goNextActivity(ManageActivity.class);
                finish();
                break;
            case R.id.save:
                if (page == Constants.EDIT_ADDRESS) {

                    getDatafromView();
                    savetoDatabase(shippingId, str_receiverName, str_phone, province, city, str_address);



                    break;
                } else if (page == Constants.ADD_ADDRESS) {
                    toastShort("新增地址");
                    getDatafromView();
                    addToDatabase(user.getId(), str_receiverName, str_phone, province, city, str_address);
                }

        }
    }

    /**
     * 从编辑视图中获取地址 电话 是否默认 姓名
     */
    private void getDatafromView() {
        str_receiverName = receiverName.getText().toString().trim();
        str_phone = phone.getText().toString().trim();
        String fullAddress = address.getText().toString().trim();
        splitaddress(fullAddress);

    }

    /**
     * 将完整地址分成 省  市   镇
     * @param address
     */
    public void splitaddress(String address) {
        char[] chars = address.toCharArray();
        StringBuilder stringBuilder = new StringBuilder();;

        for (int i = 0; i < chars.length; i++) {
            stringBuilder.append(chars[i]);
            if (chars[i] == '省') {

                province = stringBuilder.toString();

                stringBuilder = stringBuilder.delete(0, stringBuilder.length());
            } else if (chars[i] == '市') {
                city = stringBuilder.toString();
                stringBuilder = stringBuilder.delete(0, stringBuilder.length());
            } else if (i == chars.length-1){
                str_address = stringBuilder.toString();
            }
        }
        log(", province = "
                + province + ", city = " + city + ", address = " + address);

    }

    /**
     * 将修改后的数据保存到数据库
     * @param shippingId  地址id
     * @param name        收货人地址
     * @param mobile      手机号码
     * @param province    省份
     * @param city        城市
     * @param address     地址
     */
    private void savetoDatabase(int shippingId, String name, String mobile, String province, String city, String address) {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RequestInterface.basePath)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        RequestInterface.ManageAddress requestInterfaceLogin = retrofit.create(RequestInterface
                .ManageAddress.class);
        log("shippingId=" + shippingId + ", name = " + name + ", mobile = " + mobile + ", province = "
                + province + ", city = " + city + ", address = " + address);
        Call<ServerResponse> call = requestInterfaceLogin
                .updateAddress(shippingId, name, mobile, province, city, address);

        call.enqueue(new Callback<ServerResponse>() {
            @Override
            public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
                if (response.body() == null) {
                    toastShort("网络异常，" +
                            "请检查网络配置");


                    return;
                }

                if (response.body().getStatus() == 0) {

                    toastShort("更新成功！");
                    log("更新成功！");
                    //跳转页面
                    handler.removeMessages(UPDATE_SUCCESS);
                    handler.sendEmptyMessage(UPDATE_SUCCESS);

                } else {
                    toastShort("更新失败");
                    log("onRespnse: 更新失败");
                }

            }

            @Override
            public void onFailure(Call<ServerResponse> call, Throwable t) {
                Log.d(TAG, "onFailure: ");
                toastShort("更新失败");
                log("onFailure: 更新失败");
            }
        });
    }

    private void addToDatabase(int id, String name, String mobile, String province, String city, String address) {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RequestInterface.basePath)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        RequestInterface.ManageAddress requestInterfaceManage = retrofit.create(RequestInterface
                .ManageAddress.class);
        log("shippingId=" + id + ", name = " + name + ", mobile = " + mobile + ", province = "
                + province + ", city = " + city + ", address = " + address);
        Call<ServerResponse> call = requestInterfaceManage
                .addAddress(id, name, mobile, province, city, address);

        call.enqueue(new Callback<ServerResponse>() {
            @Override
            public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
                if (response.body() == null) {
                    toastShort("网络异常，" +
                            "请检查网络配置");

                    return;
                }

                if (response.body().getStatus() == 0) {

                    toastShort("添加地址成功！");
                    log("添加地址成功！");
                    //跳转页面
                    Intent intent = new Intent(getContext(), ManageActivity.class);
                    startActivity(intent);



                } else {
                    toastShort("添加地址失败");
                    log("onRespnse: 添加地址失败");
                }

            }

            @Override
            public void onFailure(Call<ServerResponse> call, Throwable t) {
                Log.d(TAG, "onFailure: ");
                toastShort("添加地址失败");
                log("onFailure: 添加地址失败");
            }
        });
    }


}
